#include "engine.h"

#include <GL/glew.h>

namespace HW
{

void _i_Enable2DDrawing ( );
void _i_Disable2DDrawing ( );

void Plot(int x, int y)
{
	_i_Enable2DDrawing();
	glBegin ( GL_POINTS );
	glVertex2i ( x , y );
	glEnd();
	_i_Disable2DDrawing();
}

void DrawLine(int x1, int y1, int x2, int y2)
{
	_i_Enable2DDrawing();
	glBegin ( GL_LINES );
	glVertex2i ( x1 , y1 );
	glVertex2i ( x2 , y2 );
	glEnd();
	_i_Disable2DDrawing();

}

void DrawRect(int x, int y, int width, int height)
{
	_i_Enable2DDrawing();
	glBegin ( GL_TRIANGLE_FAN );
	glVertex2i ( x , y );
	glVertex2i ( x+width , y );
	glVertex2i ( x+width , y+height );
	glVertex2i ( x , y+height );
	glEnd();
	_i_Disable2DDrawing();
}

void SetBlend(int blendmode)
{
	switch ( blendmode )
	{
		case BLEND_ALPHA:
			glEnable (GL_BLEND);
			glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			break;

		case BLEND_LIGHT:
			glEnable (GL_BLEND);
			glBlendFunc (GL_ONE, GL_ONE);
			break;

		case BLEND_MOD2X:
			glEnable (GL_BLEND);
			glBlendFunc (GL_DST_COLOR, GL_SRC_COLOR);
			break;

		case BLEND_SHADE:
			glEnable (GL_BLEND);
			glBlendFunc (GL_DST_COLOR, GL_ZERO);
			break;

		case BLEND_NONE:
			glDisable (GL_BLEND);
			break;
	}
}

void SetColor(const TVec4 &color)
{
	glColor4fv ( color.a );
}

void SetColor(flt r, flt g, flt b, flt a)
{
	glColor4f ( r , g , b , a );
}

void DrawImage(TTexture texture, int x, int y, int width, int height)
{
	_i_Enable2DDrawing();
	glEnableClientState ( GL_TEXTURE_COORD_ARRAY );
	BindTexture ( texture , 0 );
	glEnable ( GL_TEXTURE_2D );

	glBegin ( GL_TRIANGLE_FAN );
	glVertex2i ( x , y );
	glTexCoord2i ( 0 , 0 );
	glVertex2i ( x+width , y );
	glTexCoord2i ( 1 , 0 );
	glVertex2i ( x+width , y+height );
	glTexCoord2i ( 1 , 1 );
	glVertex2i ( x , y+height );
	glTexCoord2i ( 0 , 1 );
	glEnd();
	
	glDisable ( GL_TEXTURE_2D );
	glDisableClientState ( GL_TEXTURE_COORD_ARRAY );
	_i_Disable2DDrawing();
}


void _i_Enable2DDrawing ( )
{
	glMatrixMode(GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity();
	glOrtho ( 0.0, GraphicsWidth(), 0.0, GraphicsHeight() , 0.0 , 1.0 );
	glMatrixMode(GL_MODELVIEW );
	glPushMatrix();
	glLoadIdentity();
	glDisable(GL_DEPTH_TEST);
}

void _i_Disable2DDrawing ( )
{
	glEnable(GL_DEPTH_TEST);
	glMatrixMode(GL_PROJECTION );
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW );
	glPopMatrix();
}

}